package com.fkdx.webman.config;

import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * RestTemplate配置类
 *
 * @author yl 2024-11-25
 */
@Configuration
public class RestTemplateConfig {

    /**
     * 最大连接数
     */
    @Value("${http.maxTotal}")
    private Integer maxTotal;

    /**
     * 单个路由最大连接数
     */
    @Value("${http.defaultMaxPerRoute}")
    private Integer defaultMaxPerRoute;


    /**
     * 连接上服务器(握手成功)的时间，超出抛出connect timeout
     */
    @Value("${http.connectTimeout}")
    private Integer connectTimeout;

    /**
     * 从连接池中获取连接的超时时间，超时间未拿到可用连接，会抛出异常
     */
    @Value("${http.connectionRequestTimeout}")
    private Integer connectionRequestTimeout;

    /**
     * 服务器返回数据(response)的时间，超过抛出read timeout
     */
    @Value("${http.socketTimeout}")
    private Integer socketTimeout;

    /**
     * 最大空间时间
     */
    @Value("${http.validateAfterInactivity}")
    private Integer validateAfterInactivity;

    @Bean(name = "restTpl")
    public RestTemplate restTemplate() {
        return new RestTemplate(httpRequestFactory());
    }

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        connectionManager.setValidateAfterInactivity(validateAfterInactivity);

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .build();

        // 设置报文信息headers
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
        headers.add(new BasicHeader("Accept-Encoding", "gzip, deflate, br, zstd"));
        headers.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.9"));
        //headers.add(new BasicHeader("Connection", "Keep-Alive"));
        headers.add(new BasicHeader("Content-type", "application/json"));

        headers.add(new BasicHeader("Sec-Fetch-Site", "same-origin"));
        headers.add(new BasicHeader("Sec-Fetch-Mode", "cors"));
        headers.add(new BasicHeader("Sec-Fetch-Dest", "empty"));
        headers.add(new BasicHeader("Sec-Ch-Ua-Platform", "\"Windows\""));
        headers.add(new BasicHeader("Sec-Ch-Ua-Mobile", "?0"));
        headers.add(new BasicHeader("Sec-Ch-Ua", "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\""));
        headers.add(new BasicHeader("Origin", "https://g4b.giftee.biz"));

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .setDefaultHeaders(headers)
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
                .build();
    }
}
